#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <vector>
#include "stringhash.h"

using namespace std;


class bloomfilter
{
private:
    /* data */
    int bitsize_;
    vector<int> bitmap_;
public:
    void setbit(const char* str)
    {
        int idx1 = BKDRHash(str) % bitsize_;
        int idx2 = RSHash(str) % bitsize_;
        int idx3 = JSHash(str) % bitsize_;
        int index = idx1 / bitmap_.size();
        bitmap_[index] |= (1 << (idx1 % 32));

        index = idx2 / bitmap_.size();
        bitmap_[index] |= (1 << (idx2 % 32));

        index = idx3 / bitmap_.size();
        bitmap_[index] |= (1 << (idx3 % 32));

    }

    bool getbit(const char* str)
    {
        int idx1 = BKDRHash(str) % bitsize_;
        int idx2 = RSHash(str) % bitsize_;
        int idx3 = JSHash(str) % bitsize_;

        int index = idx1 / bitmap_.size();
        int offset = idx1 % 32;
        if (0 == (bitmap_[index] & (1 << offset)))
        {
            return false;
        }
        index = idx2 / bitmap_.size();
        offset = idx2 % 32;
        if (0 == (bitmap_[index] & (1 << offset)))
        {
            return false;
        }     

        index = idx3 / bitmap_.size();
        offset = idx3 % 32;
        if (0 == (bitmap_[index] & (1 << offset)))
        {
            return false;
        }

        return true;
    }

    bloomfilter(int size = 1471)
        : bitsize_(size)
    {
        bitmap_.resize(bitsize_/32 + 1);
    }
    ~bloomfilter(){}
};

// URL 黑名单
class BlackList {
private:
    /* data */
    bloomfilter BlackList_;

public:
    void add(string url)
    {
        cout << "add: " << url << endl;
        BlackList_.setbit(url.c_str());
    }

    bool query(string url)
    {
        cout << "query: " << url << endl;
        return BlackList_.getbit(url.c_str());
    }
};


int main(int argc, const char** argv) {
    BlackList blacklist;
    blacklist.add("www.baidu.com");
    blacklist.add("www.google.com");
    blacklist.add("www.sina.com");

    cout << blacklist.query("www.baidu.com") << endl;
    cout << blacklist.query("www.google.com") << endl;
    cout << blacklist.query("www.sina.com") << endl;
    cout << blacklist.query("www.qq.com") << endl;
    return 0;
}